var map = null;
var shapeLayer;
var lineLayer;
var leadsLayer;
var polyPoints = new Array();
var LeadsCityName = new Array();
var down = 0;
var X = 0, Y = 0;
var origin;
var MaxLat = 0;
var MinLat = 0;
var MaxLon = 0;
var MinLon = 0;
var menuLayer = null;
var IsNeedPostback = false;
var selectIndex = null;
var IsOrderPeriod = true;
var TeerQueue = new Array();
var ViewByAssignMent = false;
var CurAgentName;
var CurOrderWeek = 0;
var LeadMap;
var leadLayer;
var LockMonth;
var OrderCityName = new Array();
var MDRuleEnable;
var curMonth;
var PeriodMonth;
var PeriodYear;
var MDRuleRepeatEnable;
var CurLeadsRuleDisable;
var leadShapesWithReason = new Array();
var IsReSelectWeek = false;
var Cities;
var OtherPageOperate = '';
window.onload = function PageInti() {
    hideHeaderDiv();
    if (window.screen.width == 1024) {
        document.getElementById("myMap1").className = "divAt1024";
    }
    else if (window.screen.width == 1280) {
        document.getElementById("myMap1").className = "divAt1280";
    }
    else {
        document.getElementById("myMap1").className = "divOthers";
    }
    divmask1.style.visibility = 'visible';
    divmassage_box2.style.visibility = 'visible';
    PageMethods.GetLockMonth(CallBacklockMonth);
    PageMethods.IsRuleEnalbe(CallBackRuleEnable);
    PageMethods.IsRuleRepeatEnalbe(CallBackRuleRepeatEnable);
    PageMethods.GetSysYear(CallBackYear);
    PageMethods.GetSysMonth(CallBackMonth);
    PageMethods.GetOperateType(CallBackOperateType);
}
function create_map() {
    if (map == null) {
        map = new VEMap('myMap1');
        map.LoadMap();
    }
    map.DeleteAllShapeLayers();
    shapeLayer = new VEShapeLayer();
    map.AddShapeLayer(shapeLayer);
    map.EnableShapeDisplayThreshold(false);
    lineLayer = new VEShapeLayer();
    leadsLayer = new VEShapeLayer();
    map.AddShapeLayer(lineLayer);
    map.AddShapeLayer(leadsLayer);
    map.AttachEvent("onmouseup", MouseUpHandler);
    map.AttachEvent("onmousedown", MouseDownHandler);
    map.AttachEvent("onmousemove", MouseMoveHandler);
    BindFilterCity();
    var citySelect = document.getElementById("selectOrderCity");
    var Obj = document.getElementById("ctl00_DetailsContent_DrpOrderCounty");

    var county = Obj.options[Obj.selectedIndex].innerText;
    var countyList = new Array();
    if (county == 'All') {
        for (i = 1; i < Obj.options.length; i++) {
            countyList.push(Obj.options[i].text);
        }
    }
    else {
        countyList.push(county);
    }

    PageMethods.Pin(GetSelectItem(citySelect), countyList, curMonth, CallBack);
    PageMethods.IsOrderPeriod(CallBackIsOrderPeriod);
    map.SetZoomLevel(6);
}

function hideHeaderDiv() {
    var current = document.getElementById("header");
    current.parentNode.removeChild(current);
    current = document.getElementById("topsection");
    current.parentNode.removeChild(current);
    current = document.getElementById("breadcrumb");
    current.parentNode.removeChild(current);
}

function showHistoryWindow1() {
    divmask1.style.visibility = 'visible';
    divmassage_box1.style.visibility = 'visible';
}

function CallBack(result) {
    TeerQueue = new Array();
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    selectIndex = document.getElementById("Select1").selectedIndex;
    if (info.length > 0) {
        MaxLat = info[0].Latitude;
        MinLat = info[0].Latitude;
        MaxLon = info[0].Longitude;
        MinLon = info[0].Longitude;
    }

    AddAgentPushpin();

    for (var i in info) {
        try {
            AddPushpin(info[i].Latitude, info[i].Longitude, info[i].LeadBlockCode, info[i].ZipName, info[i].City, info[i].County, info[i].ActiveLeadCount, info[i].LapsedLeadCount, info[i].NeighborLeadCount, info[i].BusinessLeadCount, info[i].IsOrdered, info[i].UserAssigned, info[i].ZipId, info[i].LastOrderDate, info[i].SecondaryCity, info[i].IsDLA, info[i].RealActiveLeadCount, info[i].RealLapsedLeadCount);
            UpdateLatLon(info[i].Latitude, info[i].Longitude);
            BindFilterZipcode(info[i].ZipName);
        }
        catch (err) {
            alert(err);
        }
    }
    IsNeedPostback = false;

    var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
    var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
    var velatlon = new VELatLong(lat, lon);
    map.SetCenter(velatlon);

}

function CallBackleads(result) {
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    shapeLayer.Hide();
    leadsLayer.DeleteAllShapes();
    for (var i in info) {
        AddPushpinLeads(info[i].LeadId, info[i].SelPersonId, info[i].Zip, info[i].LeadBlockCode, info[i].Division, info[i].Market, info[i].County, info[i].CallType, info[i].LeadType, info[i].MdNumber, info[i].BirthDate, info[i].SequenceNumber, info[i].County, info[i].State, info[i].City, info[i].RawData, info[i].FirmName, info[i].LastName, info[i].FirstName, info[i].StreetAddress, info[i].LeadCity, info[i].LeadState, info[i].Telephone, info[i].SubSequenceNumber, info[i].Latitude, info[i].Longitude, info[i].SelDNC, info[i].PcLeadType, info[i].DncAfterDate, info[i].UserId);
        UpdateLatLon(info[i].Latitude, info[i].Longitude);
    }
    if (info.length > 0) {
        var lat = info[0].Latitude;
        var lon = info[0].Longitude;
        var velatlon = new VELatLong(lat, lon);
        map.SetCenterAndZoom(velatlon, 11);
    }

    leadsLayer.Show();
}

function CallBackIsOrderPeriod(result) {
    IsOrderPeriod = result;
}

function AddAgentPushpin() {
    var hideAgentLocation = document.getElementById("ctl00_DetailsContent_hideAgentLocation");

    if (hideAgentLocation.value.length > 5) {
        var lat = hideAgentLocation.value.split('|')[0];
        var lon = hideAgentLocation.value.split('|')[1];
        var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
        shapeLayer.AddShape(shape);
        shape.SetCustomIcon(" <img src='../Content/Images/agent.png'/> ");
        shape.SetPhotoURL('1');
    }
}

function AddPushpin(x, y, leadBlock, zipCode, city, county, active, lasped, neighbor, business, IsOrder, UserAssigned, ZipId, LastOrderDate, secondarycity, IsDLA, rActive, rLapsed) {
    var lat = x;
    var lon = y;
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
    shapeLayer.AddShape(shape);
    var Islocked = 0; //0 unlock,1 lock;
    var info = 'Zip Code:' + zipCode + '<br>Preferred City: ' + city + '<br>Active Stop Count: ' + active + '<br>Lasped Stop Count:' + lasped + '<br>Neighbor Stop Count: ' + neighbor + '<br>Business Stop Count: ' + business + '<br>Active Lead Card Count: ' + rActive + '<br>Lasped Lead Card Count:' + rLapsed + '<br>Assignment Name:' + UserAssigned + '<br>' + 'Last date ordered:' + LastOrderDate + '<br>' + "Alternate City:" + secondarycity + "<br>";
    var viewLeadText = '<br><a href="#" onclick="ViewLeads(' + "'" + ZipId + "'" + ')">View Leads</a>';
    if(IsDLA) {
        info = info + '<br>' + '<a href="#" onclick="divDefaultAssigment.style.visibility =\'visible\';divmask1.style.visibility = \'visible\';">Default Lead Assignment</a><br>';
    }
    if (MDRuleRepeatEnable && IsLockOrder(LastOrderDate)) {
        shape.SetCustomIcon("<img src='../Content/Images/pinDisable.gif'/> ");
        var LastOrderMonth = parseInt(LastOrderDate.substring(0, 2));
        var LastOrderYear = parseInt(LastOrderDate.substring(2, 6));
        LastOrderMonth = LastOrderMonth + parseInt(LockMonth);
        if (LastOrderMonth > 12) {
            LastOrderYear++;
            LastOrderMonth = LastOrderMonth - 12;
        }
        shape.SetDescription(info + '<br><div class="LockOrder"><a href="#">Cannot be added until [' + LastOrderMonth + '/' + LastOrderYear + '] lead order</a></div>');
        Islocked = 1;
    }
    else {
        if (IsOrder.toString() == 'true' || IsCurWeekLeads(UserAssigned)) {
            if (IsOrder.toString() == 'true' && IsCurWeekLeads(UserAssigned)) {
                addActive(active, lasped, neighbor, business, county);
            }
            shape.SetCustomIcon(" <img src='../Content/Images/pinOrdered.gif'/> ");
            shape.SetDescription(info + '<br><a href="#" onclick="RemoveFromCart(' + lat + ',' + lon + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + IsOrder + "','" + UserAssigned + "','" + shape.GetID() + "','" + ZipId + "','" + LastOrderDate + "','" + secondarycity + "','" +IsDLA+"'"+ ');">Remove from cart.</a><br>' + viewLeadText);
        }
        else {
            shape.SetCustomIcon("<img src='../Content/Images/" + ReturnIconName(city, LastOrderDate) + "'/> ");
            shape.SetDescription(info + '<br><a href="#" onclick="AddOrderedPushpin(' + lat + ',' + lon + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + "," + IsOrder + ",'" + UserAssigned + "','" + shape.GetID() + "','" + ZipId + "','" + LastOrderDate + "','" + secondarycity + "','" + IsDLA + "'" + ');">Add to cart.</a><br>' + viewLeadText);
        }
    }
    var LastOrder = '1';
    var lastMonthDate = document.getElementById("ctl00_DetailsContent_hideLastMonthDate").value;

    if (LastOrderDate != lastMonthDate) {
        LastOrder = '0';
    }
    shape.SetMoreInfoURL(ZipId + "|" + IsOrder + "|" + county + "|" + shape.GetCustomIcon() + "|" + active + "|" + lasped + "|" + neighbor + "|" + business + "|" + LastOrder + "|" + UserAssigned + "|" + LastOrderDate + "|" + city + "|" + Islocked+"|"+IsDLA);
    shape.SetPhotoURL('1');
}

function AddPushpinZipCodes(x, y, ZipName, county, active, lasped, neighbor, business, UserId, IsOrdered) {
    var lat = x;
    var lon = y;
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
    shapeLayer.AddShape(shape);
    var info = '<br>Zip Name:' + ZipName + '<br>County: ' + county + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>';
    if (IsOrdered) {
        shape.SetCustomIcon("<img src='../Content/Images/pinOrdered.gif'/> ");
        info += '<a href="#" onclick="ManageZipCodeToCart(1,' + lat + ',' + lon + ",'" + ZipName + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');">Remove from cart.</a>';
    }
    else {
        shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconByTeer(teer) + ".gif'/> ");
        info += '<br><a href="#" onclick="ManageZipCodeToCart(0,' + lat + ',' + lon + ",'" + ZipName + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');">Add to cart.</a><br>';
    }
    shape.SetDescription(info);
    shape.SetMoreInfoURL(ZipName + "|" + county + "|" + shape.GetCustomIcon() + "|" + active + "|" + lasped + "|" + neighbor + "|" + business + "|" + UserId + "|" + IsOrdered);
    shape.SetPhotoURL('1');
}

function AddPushpinLeads(LeadId, SelPersonId, Zip, LeadBlockCode, Division, Market, County, CallType, LeadType, MdNumber, BirthDate, SequenceNumber, County, State, City, RawData, FirmName, LastName, FirstName, StreetAddress, LeadCity, LeadState, Telephone, SubSequenceNumber, Latitude, Longitude, SelDNC, PcLeadType, DncAfterDate, UserId) {
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(Latitude, Longitude));
    leadsLayer.AddShape(shape);
    var info = "Zip+4:" + Zip + "<br>" + "LeadBlockCode:" + LeadBlockCode + "<br>" + "Division:" + Division + "<br>" + "Market:" + Market + "<br>" + "County:" + County + "<br>" + "CallType:" + CallType + "<br>" + "LeadType:" + LeadType + "<br>" + "BirthDate:" + BirthDate + "<br>" + "SequenceNumber:" + SequenceNumber + "<br>" + "FirmName:" + FirmName + "<br>" + "LastName:" + LastName + "<br>" + "FirstName:" + FirstName + "<br>" + "StreetAddress:" + StreetAddress + "<br>" + "Preferred City:" + LeadCity + "<br>" + "State:" + LeadState + "<br>" + "Telephone:" + Telephone + "<br>" + "SelDNC:" + SelDNC + "<br>" + "DncAfterDate:" + DncAfterDate + "<br>";
    info += '<br><a href="#" onclick="CloseLeadsView()" >Return</a>';
    shape.SetCustomIcon(" <img src='../Content/Images/pin3.gif'/> ");
    shape.SetDescription(info);
}
function ManageZipCodeToCart(OperateType, x, y, ZipName, county, active, lasped, neighbor, business, UserId, ShapeID) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    var shape = map.GetShapeByID(ShapeID);
    var paras = new Array();
    paras = shape.GetMoreInfoURL().split('|');
    var info = '<br>Zip Name:' + ZipName + '<br>County: ' + county + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>';
    if (OperateType == 0) {
        if (paras[8] == '0') {
            shape.SetCustomIcon(" <img src='../Content/Images/pinOrdered.gif'/> ");
            info += '<a href="#" onclick="ManageZipCodeToCart(1,' + lat + ',' + lon + ",'" + ZipName + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');SubActive(' + active + ',' + lasped + ',' + neighbor + ',' + business + ',' + county + ')">Remove from cart.</a>';
            shape.SetDescription(info);
            shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('false', 'true'));
            addActive(active, lasped, neighbor, business, county);
            PageMethods.ManagerZipCodeToCart(ZipName, OperateType);
        }
    }
    else {
        if (paras[8] == '1') {
            shape.SetCustomIcon("<img src='../Content/Images/pin" + ReturnIconInArray(teer) + ".gif'/> ");
            info += '<br><a href="#" onclick="ManageZipCodeToCart(0,' + lat + ',' + lon + ",'" + ZipName + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + ",'" + UserId + "','" + shape.GetID() + "'" + ');addActive(' + active + ',' + lasped + ',' + neighbor + ',' + business + ',' + county + ')">Add to cart.</a><br>';
            shape.SetDescription(info);
            shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
            SubActive(active, lasped, neighbor, business, county);
            PageMethods.ManagerZipCodeToCart(ZipName, OperateType);
        }
    }
}

function AddOrderedPushpin(x, y, leadBlock, zipCode, city, county, active, lasped, neighbor, business, IsOrder, UserAssigned, shapeID, ZipId, IsLastOrdered, secondarycity,IsDLA) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }

    if (!CheckMDOrderRule(active)) {
        return;
    }

    if (!IsAllowAddTocart(IsLastOrdered)) {
        CurLeadsRuleDisable = x + "," + y + "," + leadBlock + "," + zipCode + "," + city + "," + county + "," + active + "," + lasped + "," + neighbor + "," + business + "," + IsOrder + "," + UserAssigned + "," + shapeID + "," + ZipId + "," + IsLastOrdered + "," + secondarycity+","+IsDLA;
        divMustOrder.style.visibility = 'visible';
        divmask1.style.visibility = 'visible';
    }
    else {
        var shape = map.GetShapeByID(shapeID);
        if (shape.GetMoreInfoURL().indexOf("false") != -1) //confirm it had ordered .
        {
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');

            var lat = x;
            var lon = y;
            shape.SetCustomIcon(" <img src='../Content/Images/pinOrdered.gif'/> ");
            var info = 'Zip Code:' + zipCode + '<br>Preferred City: ' + city + '<br>County: ' + county + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>' + 'Assignment Name:' + CurOrderWeek + ' ' + CurAgentName + '<br>' + 'Last date ordered:' + IsLastOrdered + '<br>' + "Alternate City:" + secondarycity;
            var IsDLA = str[13];
            if (IsDLA=='true') {
                info = info + '<br>' + '<a href="#" onclick="divDefaultAssigment.style.visibility =\'visible\';divmask1.style.visibility = \'visible\';">Default Lead Assignment</a><br>';
            }
            var viewLeadText = '<br><a href="#" onclick="ViewLeads(' + "'" + ZipId + "'" + ')">View Leads</a>';
            shape.SetDescription(info + '<br><a href="#" onclick="RemoveFromCart(' + lat + ',' + lon + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + ",true,'" + CurOrderWeek + ' ' + CurAgentName + "','" + shapeID + "','" + ZipId + "','" + IsLastOrdered + "','" + secondarycity + "','" + IsDLA + "'" + ');">Remove from cart.</a>' + viewLeadText);
            var moreInfoURL = '';
            for (K = 0; K < str.length; K++) {
                if (K == 9) {
                    moreInfoURL = moreInfoURL + CurOrderWeek + ' ' + CurAgentName + '|';
                }
                else if (K == 1) {
                    moreInfoURL = moreInfoURL + 'true' + '|';
                }
                else {
                    moreInfoURL = moreInfoURL + str[K] + '|';
                }
            }
            shape.SetMoreInfoURL(moreInfoURL);
            PageMethods.ManagerZipToCart(ZipId, '0', CurAgentName, CurOrderWeek, curMonth);
            addActive(active, lasped, neighbor, business, county);
        }
    }
}

function RemoveFromCart(x, y, leadBlock, zipCode, city, county, active, lasped, neighbor, business, IsOrder, UserAssigned, shapeID, ZipId, IsLastOrdered, secondarycity,IsDLA) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    if (shapeID != null) {
        var shape = map.GetShapeByID(shapeID);
        var str = new Array();
        str = shape.GetMoreInfoURL().split('|');
        if (shape.GetMoreInfoURL().indexOf("true") != -1 || IsCurWeekLeads(UserAssigned))  //have not ordered yet.
        {
            var info = 'Zip Code:' + zipCode + '<br>Preferred City: ' + city + '<br>County: ' + county + '<br>Active Count: ' + active + '<br>Lasped Count:' + lasped + '<br>Neighbor Count: ' + neighbor + '<br>Business Count: ' + business + '<br>' + 'Assignment Name:' + '<br>' + 'Last date ordered:' + IsLastOrdered + '<br>' + 'Alternate City:' + secondarycity + "<BR>";
            var IsDLA = str[13];
            if (IsDLA == 'true') {
                info = info + '<br>' + '<a href="#" onclick="divDefaultAssigment.style.visibility =\'visible\';divmask1.style.visibility = \'visible\';">Default Lead Assignment</a><br>';
            }
            var viewLeadText = '<br><a href="#" onclick="ViewLeads(' + "'" + ZipId + "'" + ')">View Leads</a>';
            shape.SetDescription(info + '<br><a href="#" onclick="AddOrderedPushpin(' + x + ',' + y + ",'" + leadBlock + "','" + zipCode + "','" + city + "','" + county + "'," + active + "," + lasped + "," + neighbor + "," + business + ",false,'" + '' + "','" + shapeID + "'," + ZipId + ",'" + IsLastOrdered + "','" + secondarycity + "','" + IsDLA + "'" + ');">Add to cart.</a>' + viewLeadText);
            shape.SetCustomIcon("<img src='../Content/Images/" + ReturnIconName(city, str[10]) + "'/> ");

            if (IsOrder.toString() == 'true' && IsCurWeekLeads(UserAssigned)) {
                SubActive(active, lasped, neighbor, business, county);
            }
            PageMethods.ManagerZipToCart(ZipId, '1', CurAgentName, CurOrderWeek, curMonth);
            var moreInfoURL = '';
            for (K = 0; K < str.length; K++) {
                if (K == 9) {
                    moreInfoURL = moreInfoURL + ' ' + '|';
                }
                else if (K == 1) {
                    moreInfoURL = moreInfoURL + 'false' + '|';
                }
                else {
                    moreInfoURL = moreInfoURL + str[K] + '|';
                }
            }
            shape.SetMoreInfoURL(moreInfoURL);
        }
    }
}

function UnlockAndOrder(x, y, leadBlock, zipCode, city, county, active, lasped, neighbor, business, IsOrder, UserAssigned, shapeID, ZipId, IsLastOrdered, secondarycity) {
    if (confirm('You are not allowed to add before unlock date  unless special circumstances ,are you sure continue.')) {
        if (!IsOrderPeriod) {
            alert('Sorry,you can not operate now for the cut off date reached! ');
            return;
        }
        CurLeadsRuleDisable = x + "," + y + "," + leadBlock + "," + zipCode + "," + city + "," + county + "," + active + "," + lasped + "," + neighbor + "," + business + "," + IsOrder + "," + UserAssigned + "," + shapeID + "," + ZipId + "," + IsLastOrdered + "," + secondarycity;
        divMustOrder.style.visibility = 'visible';
        divmask1.style.visibility = 'visible';
    }
}

function addActive(A, L, N, B, county) {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");

    lbactive.innerHTML = parseInt(lbactive.innerHTML) + parseInt(A);
    lbbussiness.innerHTML = parseInt(lbbussiness.innerHTML) + parseInt(B);
    lblapse.innerHTML = parseInt(lblapse.innerHTML) + parseInt(L);
    lbneighbor.innerHTML = parseInt(lbneighbor.innerHTML) + parseInt(N);
}

function SubActive(A, L, N, B, county) {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");

    lbactive.innerHTML = parseInt(lbactive.innerHTML) - parseInt(A);
    lbbussiness.innerHTML = parseInt(lbbussiness.innerHTML) - parseInt(B);
    lblapse.innerHTML = parseInt(lblapse.innerHTML) - parseInt(L);
    lbneighbor.innerHTML = parseInt(lbneighbor.innerHTML) - parseInt(N);
}

function hideEachShape() {
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        shape.Hide();
    }
}

function drawPolygon() {
    //remove the polygon that is on the map

    lineLayer.DeleteAllShapes();

    //draw polyline if there is only two points in the array
    if (polyPoints.length < 3) {
        var polygon = new VEShape(VEShapeType.Polyline, polyPoints);
    }
    else {
        //create a new polygon
        var polygon = new VEShape(VEShapeType.Polygon, polyPoints);
    }
    polygon.SetZIndex(shapeLayer.GetShapeCount() + 1);
    polygon.HideIcon();

    //draw the new polygon on the map
    lineLayer.AddShape(polygon);

}


function polygonDescrption() {
    var counter = 0;
    var ordered = 0;
    var unorder = 0;
    var a = 0;
    var l = 0;
    var n = 0;
    var b = 0;
    var str = new Array();
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        var IfHidden = shape.GetPhotoURL();
        str = shape.GetMoreInfoURL().split('|');
        if (IfHidden != '0' && pointInPolygon(polyPoints, lat, lon)) {
            var icon = shape.GetCustomIcon();
            if (icon.substr(icon.lastIndexOf('.') - 2, 2) == '10')  //Decide if order,because the order pushpin's icon is pinOrdered.gif
            {
                ordered++;
            }
            else {
                unorder++;
            }
        }
        if (!IsNeedPostback && pointInPolygon(polyPoints, lat, lon) && str[1] == 'false') {

            a = a + parseInt(str[4]);
            l = l + parseInt(str[5]);
            n = n + parseInt(str[6]);
            b = b + parseInt(str[7]);
        }
    }
    var info = '';

    if (!IsNeedPostback) {
        info = "Your totals so far are:<br>&nbsp;&nbsp;&nbsp;Acitve:" + a + "<br>&nbsp;&nbsp;&nbsp;Lasped:" + l + "<br>&nbsp;&nbsp;&nbsp;Neighbor:" + n + "<br>&nbsp;&nbsp;&nbsp;Business:" + b;
        info += "<br>&nbsp;&nbsp;&nbsp;<a href='#' onclick='polygonManagerToCart(0);'  >Add to cart. </a>";
        info += "<br>&nbsp;&nbsp;&nbsp; <a href='#' onclick='polygonManagerToCart(1);'  >Remove from cart. </a>";
        //info += "<br>&nbsp;&nbsp;&nbsp;<a href='#' onclick='polygonAssign();'  >Assign Agent</a>";
    }
    else {
        info = "<br>&nbsp;&nbsp;&nbsp;<a href='#' onclick='polygonManagerZipCodeToCart(0);'  >Add to cart. </a>";
        info += "<br>&nbsp;&nbsp;&nbsp; <a href='#' onclick='polygonManagerZipCodeToCart(1);'  >Remove from cart. </a>";
    }
    lineLayer.DeleteAllShapes();
    if (polyPoints.length < 3) {
        var polygon = new VEShape(VEShapeType.Polyline, polyPoints);
    }
    else {
        var polygon = new VEShape(VEShapeType.Polygon, polyPoints);
    }
    if (!(ordered == 0 && unorder == 0)) {
        var menuLayer1 = document.getElementById('divPolygon');
        menuLayer1.style.position = "absolute";
        menuLayer1.style.top = window.event.clientY;
        menuLayer1.style.left = window.event.clientX;
        menuLayer1.style.width = "160px";
        menuLayer1.style.height = "170px";
        menuLayer1.style.zIndex = shapeLayer.GetShapeCount() + 100;
        var contentmenu = document.getElementById('PolyMenuContent');
        contentmenu.innerHTML = info;
        menuLayer1.style.visibility = 'visible';
    }
    polygon.HideIcon();
    lineLayer.AddShape(polygon);
    menuLayer = true;
}

function polygonAssign() {
    divmassage_box1.style.visibility = 'visible';
    divmask1.style.visibility = 'visible';
}
function polygonManagerToCart(operate) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }

    leadShapesWithReason = new Array();
    var counter = 0;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        var str = new Array();
        var IfHidden = shape.GetPhotoURL();
        if (IfHidden != '0' && pointInPolygon(polyPoints, lat, lon)) {
            var description = shape.GetDescription();
            str = shape.GetMoreInfoURL().split('|');
            var teer = str[2];
            var isLock = str[12];
            var LastOrderDate = str[10];
            if (operate == '0' && str[1] == 'false' && isLock == '0') {
                if (!CheckMDOrderRule(str[4])) {
                    return;
                }

                if (IsAllowAddTocart(LastOrderDate)) {
                    description = description.replace('AddOrderedPushpin', 'RemoveFromCart');
                    description = description.replace('Add to cart', 'Remove from cart');
                    description = description.replace(',false,', ',true,');
                    description = description.replace("'null'", "'" + CurOrderWeek + ' ' + CurAgentName + "'");
                    description = UpdateDescrptionAssignMent(description, '0');
                    PageMethods.ManagerZipToCart(str[0], '0', CurAgentName, CurOrderWeek, curMonth);
                    shape.SetCustomIcon(" <img src='../Content/Images/pinOrdered.gif'/> ");
                    addActive(str[4], str[5], str[6], str[7], str[2]);
                    var moreInfoURL = '';
                    for (K = 0; K < str.length; K++) {
                        if (K == 9) {
                            moreInfoURL = moreInfoURL + CurOrderWeek + ' ' + CurAgentName + '|';
                        }
                        else if (K == 1) {
                            moreInfoURL = moreInfoURL + 'true' + '|';
                        }
                        else {
                            moreInfoURL = moreInfoURL + str[K] + '|';
                        }
                    }
                    shape.SetMoreInfoURL(moreInfoURL);
                }
                else {
                    leadShapesWithReason.push(shape.GetID()); //Let thed shape id to array which leads allow to add with reason
                }
            }
            if (operate == '1' && str[1] == 'true') {
                description = description.replace('RemoveFromCart', 'AddOrderedPushpin');
                description = description.replace('Remove from cart', 'Add to cart');
                description = description.replace(',true,', ',false,');
                description = description.replace("'" + CurOrderWeek + ' ' + CurAgentName + "'", "'null'");
                description = UpdateDescrptionAssignMent(description, '1');
                PageMethods.ManagerZipToCart(str[0], '1', CurAgentName, CurOrderWeek, curMonth);
                shape.SetCustomIcon("<img src='../Content/Images/" + ReturnIconName(str[11], str[10]) + "'/> ");
                if (str[1] == 'true' && IsCurWeekLeads(str[9])) {
                    SubActive(parseInt(str[4]), parseInt(str[5]), parseInt(str[6]), parseInt(str[7]), parseInt(str[2]));
                }
                var moreInfoURL = '';
                for (K = 0; K < str.length; K++) {
                    if (K == 9) {
                        moreInfoURL = moreInfoURL + ' ' + '|';
                    }
                    else if (K == 1) {
                        moreInfoURL = moreInfoURL + 'false' + '|';
                    }
                    else {
                        moreInfoURL = moreInfoURL + str[K] + '|';
                    }
                }
                shape.SetMoreInfoURL(moreInfoURL);
                if (menuLayer != null) {
                    lineLayer.DeleteAllShapes();
                    var menuLayer1 = document.getElementById('divPolygon');
                    menuLayer1.style.visibility = 'hidden';
                    menuLayer = null;
                }
            }
            shape.SetDescription(description);
        }
    }
    if (leadShapesWithReason.length > 0) {
        document.getElementById("divMustOrder1").style.visibility = 'visible';
        document.getElementById("divmask1").style.visibility = 'visible';
    }
}
function polygonToCartRuleWithReason() {
    var reason = document.getElementById('textarea1');
    if (reason.selectedIndex == 0) {
        alert('Please select the reason .');
        return;
    }

    for (i = 0; i < leadShapesWithReason.length; i++) {
        var shape = shapeLayer.GetShapeByID(leadShapesWithReason[i]);
        var description = shape.GetDescription();
        str = shape.GetMoreInfoURL().split('|');

        if (!CheckMDOrderRule(str[4])) {
            return;
        }

        var teer = str[2];
        PageMethods.InsertRepeatEnable(curMonth, str[0], reason.options[reason.selectedIndex].innerText)
        description = description.replace('AddOrderedPushpin', 'RemoveFromCart');
        description = description.replace('Add to cart', 'Remove from cart');
        description = description.replace(',true,', ',false,');
        description = description.replace("'" + CurOrderWeek + ' ' + CurAgentName + "'", "'null'");
        description = UpdateDescrptionAssignMent(description, '0');
        PageMethods.ManagerZipToCart(str[0], '0', CurAgentName, CurOrderWeek, curMonth);
        shape.SetCustomIcon(" <img src='../Content/Images/pinOrdered.gif'/> ");
        addActive(str[4], str[5], str[6], str[7], str[2]);
        var moreInfoURL = '';
        for (K = 0; K < str.length; K++) {
            if (K == 9) {
                moreInfoURL = moreInfoURL + CurOrderWeek + ' ' + CurAgentName + '|';
            }
            else if (K == 1) {
                moreInfoURL = moreInfoURL + 'true' + '|';
            }
            else {
                moreInfoURL = moreInfoURL + str[K] + '|';
            }
        }
        shape.SetMoreInfoURL(moreInfoURL);
    }
    shape.SetDescription(description);
    reason.selectedIndex = 0;
    document.getElementById("divMustOrder1").style.visibility = 'hidden';
    document.getElementById("divmask1").style.visibility = 'hidden';
}
function polygonManagerZipCodeToCart(operate) {
    if (!IsOrderPeriod) {
        alert('Sorry,you can not operate now for the cut off date reached! ');
        return;
    }
    var counter = 0;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;
        var str = new Array();
        if (pointInPolygon(polyPoints, lat, lon)) {
            var description = shape.GetDescription();
            str = shape.GetMoreInfoURL().split('|');
            var teer = str[1];

            if (operate == '0' && str[8] == 'false') {
                description = description.replace('ManageZipCodeToCart(0', 'ManageZipCodeToCart(1');
                description = description.replace('Add to cart', 'Remove from cart');
                shape.SetCustomIcon("<img src='../Content/Images/pinOrdered.gif'/> ");
                PageMethods.ManagerZipCodeToCart(str[0], operate);
                addActive(str[3], str[4], str[5], str[6], str[1]);
                shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('false', 'true'));
            }
            if (operate == '1' && str[8] == 'true') {
                description = description.replace('ManageZipCodeToCart(1', 'ManageZipCodeToCart(0');
                description = description.replace('Remove from cart', 'Add to cart');
                shape.SetCustomIcon("<img src='../Content/Images/pin" + teer.substring(teer.length - 1) + ".gif'/> ");
                SubActive(str[3], str[4], str[5], str[6], str[1]);
                PageMethods.ManagerZipCodeToCart(str[0], operate);
                shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
                if (menuLayer != null) {
                    lineLayer.DeleteAllShapes();
                    var menuLayer1 = document.getElementById('divPolygon');
                    menuLayer1.style.visibility = 'hidden';
                    menuLayer = null;
                }
            }
            shape.SetDescription(description);
        }
    }
}

function pointInPolygon(points, lat, lon) {
    var i;
    var j = points.length - 1;
    var inPoly = false;

    for (i = 0; i < points.length; i++) {

        if (points[i].Longitude < lon && points[j].Longitude >= lon || points[j].Longitude < lon && points[i].Longitude >= lon) {
            if (points[i].Latitude + (lon - points[i].Longitude) / (points[j].Longitude - points[i].Longitude) * (points[j].Latitude - points[i].Latitude) < lat) {
                inPoly = !inPoly;
            }
        }
        j = i;
    }

    return inPoly;
}

function MouseUpHandler(e) {
    if (e.leftMouseButton) {
        if (down == 1) {
            down = 0;
            polyPoints.push(origin);
            polygonDescrption();
            X = 0;
            Y = 0;
        }
        else {
            var menuLayer1 = document.getElementById('divPolygon');
            if (menuLayer != null) {
                menuLayer1.style.visibility = 'hidden';
                lineLayer.DeleteAllShapes();
                menuLayer = null;
            }
        }
    }
}

function MouseDownHandler(e) {
    if (shapeLayer.IsVisible()) {
        if (e.rightMouseButton) {
            X = e.mapX;
            Y = e.mapY;
            var point = map.PixelToLatLong(new VEPixel(X, Y));
            if (down == 0) {
                //intialize the map and variables.                       
                lineLayer.DeleteAllShapes();
                if (menuLayer != null) {
                    var menuLayer1 = document.getElementById('divPolygon');
                    menuLayer1.style.visibility = 'hidden';
                    menuLayer = null;
                }
                polyPoints = new Array(0);
                origin = point;
                polyPoints.push(origin);
                down = 1;
            }
            //add the new point to the array
            polyPoints.push(point);
            menuKey = true;
            return true;
        }
    }
}

function MouseMoveHandler(e) {
    if (down == 1) {
        var x = e.mapX;
        var y = e.mapY;

        var dx = Math.abs(X) - Math.abs(x);
        var dy = Math.abs(Y) - Math.abs(y);

        //do not want to redraw polygon unless we move a significant amount
        if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
            var latlong = map.PixelToLatLong(new VEPixel(x, y));
            polyPoints.pop();
            polyPoints.push(latlong);
            drawPolygon();
        }
    }
}

function UnSelectAll() {
    if (confirm("Are you sure you are going to removed all leads from cart ?")) {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            var latlong = shape.GetPoints()[0];
            var lat = latlong.Latitude;
            var lon = latlong.Longitude;
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            var teer;
            var isOrder;
            if (!IsNeedPostback) {
                teer = str[2];
                isOrder = str[1];
            }
            else {
                teer = str[1];
                isOrder = str[8];
            }
            if (isOrder == 'true') {
                var description = shape.GetDescription();
                if (!IsNeedPostback) {
                    shape.SetDescription(description.replace('RemoveFromCart', 'AddOrderedPushpin').replace('Remove from cart', 'Add to cart'));
                    PageMethods.ManagerZipToCart(str[0], '1', CurAgentName, CurOrderWeek, curMonth);
                    shape.SetCustomIcon("<img src='../Content/Images/" + ReturnIconName(str[11], str[10]) + "'/> ");
                    shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
                }
                else {
                    shape.SetDescription(description.replace('ManageZipCodeToCart(1', 'ManageZipCodeToCart(0').replace('Remove from cart', 'Add to cart'));
                    shape.SetCustomIcon("<img src='../Content/Images/" + ReturnIconName(str[11], str[10]) + "'/> ");
                    shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('true', 'false'));
                    PageMethods.ManagerZipCodeToCart(str[0], 1);
                }
                clearSummary();
            }
        }
    }
}

function ViewLeads(ZIPId) {
    PageMethods.LeadsPin(ZIPId, CallBackleads);
}

function FilterLeads() {
    if (!shapeLayer.IsVisible()) {
        map.SetZoomLevel(7);
        leadsLayer.Hide();
        shapeLayer.Show();
    }
    ShowAllLead();
    var SelectZip = document.getElementById("selectFilterZip").options[document.getElementById("selectFilterZip").selectedIndex].value;
    var SelectCity = document.getElementById("selectFilterCity").options[document.getElementById("selectFilterCity").selectedIndex].value;
    SelectCity = " " + SelectCity.replace(/(^s*)|(s*$)/g, "");
    var IsIntiLatLon = false;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        str = shape.GetMoreInfoURL().split('|');
        switch (selectIndex) {
            case 0:
                {
                    if (str[1] == 'false') {
                        shape.Hide();
                        shape.SetPhotoURL('0');
                        continue;
                    }
                    break;
                }
            case 1:
                {
                    shape.Show();
                    shape.SetPhotoURL('1');
                    break;
                }
            case 2:
                {
                    var assign = str[9];
                    assign = assign.replace(/(^\s*)|(\s*$)/g, "");
                    if (assign == 'null' || assign == '') {
                        shape.Hide();
                        shape.SetPhotoURL('0');
                        continue;
                    }
                    else if (assign != 'null' && assign !== '') {
                        shape.Show();
                        shape.SetPhotoURL('1');
                        shape.SetCustomIcon("<img src='../Content/Images/pin" + SubLastChar(ReturnIconInArray(str[9])) + ".gif'/> ");
                    }
                    break;
                }
            case 3:
                {
                    if (str[8] == '0') {
                        shape.Hide();
                        shape.SetPhotoURL('0');
                        continue;
                    }
                    else {
                        shape.Show();
                        shape.SetPhotoURL('1');
                    }
                    break;
                }
        }

        if (SelectZip != 0) {
            var description = shape.GetDescription();
            var leadZip = getMiddeStr(description, "Zip Code:", "<br>Preferred City:");
            if (SelectZip != leadZip) {
                shape.Hide();
                shape.SetPhotoURL('0');
                continue;
            }
        }

        if (SelectCity != 0) {
            var description = shape.GetDescription();
            var leadCity = getMiddeStr(description, "Preferred City:", "<br>County:");
            if (SelectCity.substring(0, 4) != leadCity.substring(0, 4)) {
                shape.Hide();
                shape.SetPhotoURL('0');
                continue;
            }
        }
        if (shape.GetPhotoURL() != '0') {
            var velatlon = shape.GetPoints();
            if (!IsIntiLatLon) {
                MaxLat = velatlon[0].Latitude;
                MinLat = velatlon[0].Latitude;
                MaxLon = velatlon[0].Longitude;
                MinLon = velatlon[0].Longitude;
                IsIntiLatLon = true;
            }
            UpdateLatLon(velatlon[0].Latitude, velatlon[0].Longitude);
        }

    }

    if (IsIntiLatLon) {
        var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
        var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
        velatlon = new VELatLong(lat, lon);
        if (SelectCity == 0 && SelectZip == 0) {
            map.SetCenterAndZoom(velatlon, 7);
        }
        else {
            map.SetCenterAndZoom(velatlon, 9);
        }
    }
}

function ResetPushpin() {
    selectIndex = document.getElementById("Select1").selectedIndex;
    if (ViewByAssignMent) {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            str = shape.GetMoreInfoURL().split('|');
            if (shape.GetPhotoURL() != '2') {
                shape.Show();
                shape.SetPhotoURL('1');
                if (str[1] != 'true') {
                    shape.SetCustomIcon("<img src='../Content/Images/" + ReturnIconName(str[11], str[10]) + "'/> ");
                }
                else {
                    shape.SetCustomIcon(" <img src='../Content/Images/pinOrdered.gif'/> ");
                }
            }
        }
        ViewByAssignMent = false;
    }
    if (selectIndex == 2) {
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            str = shape.GetMoreInfoURL().split('|');
            var assign = str[9];
            assign = assign.replace(/(^\s*)|(\s*$)/g, "");
            if (assign != 'null' && assign !== '') {
                shape.Show();
                shape.SetPhotoURL('1');
                shape.SetCustomIcon("<img src='../Content/Images/pin" + SubLastChar(ReturnIconInArray(str[9])) + ".gif'/> ");
            }
        }
        ViewByAssignMent = true;
    }
}

function clearSummary() {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbsum = document.getElementById("ctl00_InfoContent_lbCartAgent");
    var lbremain = document.getElementById("ctl00_InfoContent_lblRemain");

    if (lbneighbor != null) {
        lbneighbor.innerHTML = '0';
    }
    if (lbactive != null) {
        lbactive.innerHTML = '0';
    }
    if (lbbussiness != null) {
        lbbussiness.innerHTML = '0';
    }
    if (lbneighbor != null) {
        lblapse.innerHTML = '0';
    }
    if (lbsum != null) {
        lbsum.innerHTML = '0';
    }
    if (lbremain != null) {
        lbremain.innerHTML = '0';
    }
}

function polygonAssignZips(agentID)  //if agentID is 0,then clear assign,others assgin to agenID
{
    divmassage_box1.style.visibility = 'hidden';
    divmask1.style.visibility = 'hidden';
    var curYear = curdate.getFullYear();
    var Obj = document.getElementById("ctl00_DetailsContent_drpOrderMonth");
    var curMonth = Obj.options[Obj.selectedIndex].innerText;
    var agentName = document.getElementById("ctl00_DetailsContent_drpAssignment").options[document.getElementById("ctl00_DetailsContent_drpAssignment").selectedIndex].text;
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var latlong = shape.GetPoints()[0];
        var lat = latlong.Latitude;
        var lon = latlong.Longitude;

        if (pointInPolygon(polyPoints, lat, lon)) {
            var str = new Array();
            str = shape.GetMoreInfoURL().split('|');
            if (agentID != '0') {
                PageMethods.AssignZips(str[0], agentID, curMonth, curYear);
                var description = shape.GetDescription();
                var description1 = description.substring(description.indexOf("Assignment Name:") + 16);
                description = description.substring(0, description.indexOf("Assignment Name:") + 16) + agentName + description1.substring(description1.indexOf("<br>"));
                shape.SetDescription(description);
            }
        }
    }
    var drpAssign = document.getElementById("ctl00_DetailsContent_drpAssignment");
    drpAssign.selectedIndex = 0;
}

function ShowAssignDiv() {
    var menuLayer1 = document.getElementById('divPolygon');
    menuLayer1.style.visibility = 'hidden';
    lineLayer.DeleteAllShapes();
    menuLayer = null;
    polygonAssignZips(document.getElementById('ctl00_DetailsContent_drpAssignment').options[document.getElementById('ctl00_DetailsContent_drpAssignment').selectedIndex].value);
    divmassage_box1.style.visibility = 'hidden';
    divmask1.style.visibility = 'hidden';
}

function ReturnIconByTeer(teer) {
    if (TeerQueue.length != 0) {
        if (TeerQueue[TeerQueue.length - 1] != teer) {
            TeerQueue.push(teer);
        }
        return TeerQueue.length - 1;
    }
    else {
        TeerQueue.push(teer);
        return 0;
    }
}

function ReturnIconInArray(teer) {
    for (var i = 0; i < TeerQueue.length; i++) {
        if (TeerQueue[i] == teer) {
            return i;
        }
    }
    TeerQueue.push(teer);
    return TeerQueue.length - 1;
}

function SubLastChar(str) {
    str = String(str);
    str = str.charAt(str.length - 1);
    return str;
}

function UpdateLatLon(lat, lon) {
    if (lat > MaxLat) {
        MaxLat = lat;
    }
    else if (lat < MinLat) {
        MinLat = lat;
    }

    if (lon > MaxLon) {
        MaxLon = lon;
    }
    else if (lon < MinLon) {
        MinLon = lon;
    }

}

function ShowAllLead() {
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        shape.SetPhotoURL('1');
        shape.Show();
    }
}

function getMiddeStr(str, startStr, endStr) {
    var start = str.indexOf(startStr) + startStr.length;
    var end = str.indexOf(endStr);
    var returnStr = str.substring(start, end);
    returnStr.replace(/(^s*)|(s*$)/g, "");
    return returnStr;
}

function CloseLeadsView() {
    if (!shapeLayer.IsVisible()) {
        leadsLayer.DeleteAllShapes();
        leadsLayer.Hide();
        shapeLayer.Show();
        IsIntiLatLon = false;
        for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
            var shape = shapeLayer.GetShapeByIndex(i);
            if (shape.GetPhotoURL() != '0') {
                var velatlon = shape.GetPoints();
                if (!IsIntiLatLon) {
                    MaxLat = velatlon[0].Latitude;
                    MinLat = velatlon[0].Latitude;
                    MaxLon = velatlon[0].Longitude;
                    MinLon = velatlon[0].Longitude;
                    IsIntiLatLon = true;
                }
                UpdateLatLon(velatlon[0].Latitude, velatlon[0].Longitude);
            }
        }
        var lat = (parseFloat(MaxLat) + parseFloat(MinLat)) / 2.0;
        var lon = (parseFloat(MaxLon) + parseFloat(MinLon)) / 2.0;
        velatlon = new VELatLong(lat, lon);
        map.SetCenterAndZoom(velatlon, 7);
    }
}

function CheckMDOrderRule(activecount) {
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbUpper = document.getElementById("ctl00_InfoContent_lblUpper").innerHTML;
    var lbLower = document.getElementById("ctl00_InfoContent_lblLower").innerHTML;
    if (MDRuleEnable) {
        if (parseInt(lbactive.innerHTML) + parseInt(activecount) > parseInt(lbUpper)) {
            alert('The active stops must be between ' + lbLower + ' and ' + lbUpper + ',please select agian.');
            return false;
        }
    }

    return true;
}

function NextWeek() {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbUpper = document.getElementById("ctl00_InfoContent_lblUpper").innerHTML;
    var lbLower = document.getElementById("ctl00_InfoContent_lblLower").innerHTML;
    if (MDRuleEnable) {
        if (parseInt(lbactive.innerHTML) > parseInt(lbUpper) || parseInt(lbactive.innerHTML) < parseInt(lbLower)) {
            alert('The active stops must be between ' + lbLower + ' and ' + lbUpper + ',please select agian.');
            return;
        }
    }
    lbactive.innerHTML = 0;
    lbbussiness.innerHTML = 0;
    lblapse.innerHTML = 0;
    lbneighbor.innerHTML = 0;
    var Obj = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
    var btn = document.getElementById("btnNextWeeek");
    if (CurOrderWeek < Obj.options[Obj.selectedIndex].innerText) {
        CurOrderWeek++;
    }
    document.getElementById("spanWeek").innerText = CurOrderWeek;
    document.getElementById("spanWeek1").innerText = CurOrderWeek;
    document.getElementById("ctl00_InfoContent_lblInfoWeek").innerText = CurOrderWeek;
    PageMethods.SetCurrentWeek(CurOrderWeek);

    if (CurOrderWeek >= Obj.options[Obj.selectedIndex].innerText) {
        btn.setAttribute('disabled', 'disabled');
        var btn1 = document.getElementById("btnweek");
        btn1.removeAttribute('disabled');
        
    }
//    divmessage_box3.style.visibility = 'visible';
//    divmask1.style.visibility = 'visible';
}

function ShowFilters0() {
    divmask1.style.visibility = 'visible';
    divmassage_box2.style.visibility = 'visible';
}
function ShowFilters1() {
    var Obj = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
    var LblAgent = document.getElementById("ctl00_InfoContent_lblInfoAgent");
    var LblWeek = document.getElementById("ctl00_InfoContent_lblInfoWeek");
    var btn = document.getElementById("btnNextWeeek");
    var drpAgent = document.getElementById("ctl00_DetailsContent_drpOrderAgent");

    var message = 'You are about to place a ' + Obj.options[Obj.selectedIndex].innerText + ' week order for ';
    message = message + drpAgent.options[drpAgent.selectedIndex].innerText;
    message = message + ', please select "OK" if this is correct or "Cancel" if not correct. ';
    message = message + '\nNote: Once you select "OK" and you finish ordering your last week for your agent, ';
    message = message + 'his/her name will no longer be in the agent drop down menu to choose from again.';

    if (!confirm(message)){
        return;
    }

    if (IsReSelectWeek) {
        if (parseInt(Obj.options[Obj.selectedIndex].innerText) > parseInt(LblWeek.innerText)) {
            alert('The week number must be less than the current week number');
            return;
        }
        else {
            if (parseInt(Obj.options[Obj.selectedIndex].innerText) == parseInt(LblWeek.innerText)) {
                var btn = document.getElementById("btnNextWeeek");
                btn.setAttribute('disabled', 'disabled');
                var btn1 = document.getElementById("btnweek");
                btn1.removeAttribute('disabled');

            }
            document.getElementById("ctl00_DetailsContent_drpOrderAgent").removeAttribute('disabled');
            document.getElementById("ctl00_DetailsContent_drpOrderMonth").removeAttribute('disabled');
            document.getElementById("Next1").removeAttribute('disabled');
            divmask1.style.visibility = 'hidden';
            divmassage_box2.style.visibility = 'hidden';
            document.getElementById("btnNext").value = "Next";
            IsReSelectWeek = false;
            if (OtherPageOperate.length != 0) {
                create_map();
                PageMethods.ClearPara();
            }

            return;
        }
    }

    SetDefaultTerrAndAgentLocation();

    if (CurOrderWeek < Obj.options[Obj.selectedIndex].innerText) {
        CurOrderWeek++;
    }
    if (CurOrderWeek >= Obj.options[Obj.selectedIndex].innerText) {
        var btn = document.getElementById("btnNextWeeek");
        btn.setAttribute('disabled', 'disabled');
        var btn1 = document.getElementById("btnweek");
        btn1.removeAttribute('disabled');
    }

    Obj = document.getElementById("ctl00_DetailsContent_DrpOrderCounty");
    var county = Obj.options[Obj.selectedIndex].innerText;
    var countyList = new Array();
    if (county == 'All') {
        for (i = 1; i < Obj.options.length; i++) {
            countyList.push(Obj.options[i].text);
        }
    }
    else {
        terrList.push(county);
    }
    PageMethods.BindCity(countyList, CallBackBindCity);
    Obj = document.getElementById("ctl00_DetailsContent_drpOrderMonth");
    document.getElementById("spanMonth").innerText = Obj.options[Obj.selectedIndex].innerText;
    curMonth = Obj.options[Obj.selectedIndex].value;
    divmessage_box3.style.visibility = 'visible';
    if (Obj.selectedIndex != 0) {
        divmessage_box3.style.visibility = 'hidden';
        document.getElementById("divAlert").style.visibility = 'visible';
        // alert("Because you selected a month other than the current month you order will be saved,but you will need to log in and go to the shopping cart to place your order for this month");
    }
    LblWeek.innerText = CurOrderWeek;
    document.getElementById("spanWeek").innerText = CurOrderWeek;
    document.getElementById("spanWeek1").innerText = CurOrderWeek;
    Obj = document.getElementById("ctl00_DetailsContent_drpOrderAgent");
    document.getElementById("spanAgent1").innerText = Obj.options[Obj.selectedIndex].innerText;
    document.getElementById("spanAgent2").innerText = Obj.options[Obj.selectedIndex].innerText;
    CurAgentName = Obj.options[Obj.selectedIndex].innerText;
    Obj = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
    PageMethods.SetAgentNameAndLocation(CurAgentName, CurOrderWeek, curMonth, Obj.options[Obj.selectedIndex].value, CallBackSetAgentLocation);
    LblAgent.innerText = CurAgentName;
    divmassage_box2.style.visibility = 'hidden';
}

function CallBackSetAgentLocation(result) {
    var hideAgentLocation = document.getElementById("ctl00_DetailsContent_hideAgentLocation");
    hideAgentLocation.value = result;
}

function SetDefaultTerrAndAgentLocation() {
    
    var drpCounty = document.getElementById("ctl00_DetailsContent_DrpOrderCounty");
    var hideTerr = document.getElementById("ctl00_DetailsContent_hideAgentTerr");
    for (i = 0; i < drpCounty.options.length; i++) {
        if (hideTerr.value == drpCounty.options[i].innerText) {
            drpCounty.options[i].selected = "selected";
            return;
        }
    }

    drpCounty.options[0].selected = "selected";
}

function CallBackTeerWhichAgent(result) {
    var hideTerr = document.getElementById("ctl00_DetailsContent_hideAgentTerr");
    hideTerr.value = result;
}

function CallBackBindCity(result) {
    var cities = new Array();
    var indexs = new Array();
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    var selectCity = document.getElementById("selectOrderCity");
    if (selectCity.length != 0) {
        for (i = 0; i < selectCity.length; i++) {
            cities.push(selectCity.options[i].text);
        }

        selectCity.length = 0;
        //cities = cities.reverse()
    }

    for (i = 0; i < info.length; i++) {
        addItemToSelect(selectCity, info[i], info[i]);
        for (j = 0; j < cities.length; j++) {
            if (info[i] == cities[j]) {
                indexs.push(i);
                //selectCity.options[i].selected = "selected";
                break;
            }
        }
    }

    indexs = indexs.reverse();
    for (i = 0; i < indexs.length; i++) {
        var index = indexs[i];
        selectCity.options[index].selected = "selected";
    }
}

function addItemToSelect(objSelect, objItemText, objItemValue) {
    var varItem = new Option(objItemText, objItemValue);
    objSelect.options.add(varItem);
}


function GetSelectItem(oListbox) {
    selectIndexStr = "";
    for (i = 0; i < oListbox.options.length; i++) {
        if (oListbox.options[i].selected) {
            selectIndexStr = selectIndexStr + "|" + oListbox.options[i].innerText;
        }
    }
    return selectIndexStr;
}

function UpdateCityByCounty() {
    var Obj = document.getElementById("ctl00_DetailsContent_DrpOrderCounty");
    var county = Obj.options[Obj.selectedIndex].innerText;
    var countyList = new Array();
    if (county == 'All') {
        for (i = 1; i < Obj.options.length; i++) {
            countyList.push(Obj.options[i].text);
        }
    }
    else {
        countyList.push(county);
    }
    PageMethods.BindCity(countyList, CallBackBindCity);
}

function UpdateTerrByAgent() {
    var Obj = document.getElementById("ctl00_DetailsContent_drpOrderAgent");
    var selectAgent = Obj.options[Obj.selectedIndex].innerText;

    PageMethods.TeerByAgentName(selectAgent, CallBackTeerWhichAgent);
}

function BindFilterCity() {
    var olistbox = document.getElementById("selectOrderCity");
    var filterCity = document.getElementById("selectFilterCity");
    for (i = 0; i < olistbox.options.length; i++) {
        if (olistbox.options[i].selected) {
            var obj = new Option(olistbox.options[i].text, olistbox.options[i].value);
            filterCity.options.add(obj);
        }
    }

}
function BindFilterZipcode(zipCode) {
    var filterZip = document.getElementById("selectFilterZip");
    for (var i = 0; i < filterZip.options.length; i++) {
        if (filterZip.options[i].text == zipCode) {
            return;
        }
    }
    var obj = new Option(zipCode, zipCode);
    filterZip.options.add(obj);
}
function GoToMap() {
    j = 0;
    var olistbox = document.getElementById("selectOrderCity");
    for (i = 0; i < olistbox.options.length; i++) {
        if (olistbox.options[i].selected) {
            j++;
        }
    }
    if (j == 0) {
        alert("Please select at least one in the city dropdown list.");
        return;
    }
    divmessage_box3.style.visibility = 'hidden';
    divmask1.style.visibility = 'hidden';
    var filterCity = document.getElementById("selectFilterCity");
    filterCity.options.length = 1;
    var filterZip = document.getElementById("selectFilterZip");
    filterZip.options.length = 1;

    var Obj = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
    var LblAgent = document.getElementById("ctl00_InfoContent_lblInfoAgent");
    CurAgentName = LblAgent.innerText;
    PageMethods.SetAgentNameAndLocation(CurAgentName, CurOrderWeek, curMonth, Obj.options[Obj.selectedIndex].value, CallBackSetAgentLocation);
    create_map();
}

function CreateLeadsMap() {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lbUpper = document.getElementById("ctl00_InfoContent_lblUpper").innerHTML;
    var lbLower = document.getElementById("ctl00_InfoContent_lblLower").innerHTML;
    if (MDRuleEnable) {
        if (parseInt(lbactive.innerHTML) > parseInt(lbUpper) || parseInt(lbactive.innerHTML) < parseInt(lbLower)) {
            alert('The active stops must be between ' + lbLower + ' and ' + lbUpper + ',please select agian.');
            return;
        }
    }

    divmask1.style.visibility = 'visible';
    divMapLead.style.visibility = 'visible';
    mapWithLeads.style.visibility = 'visible';
    var divLoad = document.getElementById("divLoading");
    divLoad.style.visibility = 'visible';
    LeadMap = new VEMap('mapWithLeads');
    LeadMap.LoadMap();
    leadLayer = new VEShapeLayer();
    LeadMap.AddShapeLayer(leadLayer);
    LeadsCityName = new Array();
    var LblAgent = document.getElementById("ctl00_InfoContent_lblInfoAgent");
    CurAgentName = LblAgent.innerText;

    zipIds = new Array();
    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var str = new Array();
        str = shape.GetMoreInfoURL().split('|');
        var teer;
        var isOrder;

        if (!IsNeedPostback) {
            teer = str[2];
            isOrder = str[1];
        }
        else {
            teer = str[1];
            isOrder = str[8];
        }

        assignmentName = CurOrderWeek + ' ' + CurAgentName;
        if (isOrder == 'true' && str[9] == assignmentName) {
            zipIds.push(str[0])
        }
    }
    PageMethods.LeadsPinWithCity(zipIds, CallBackleadsByCity);

}

function CallBackleadsByCity(result) {
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    leadLayer.DeleteAllShapes();
    for (var i in info) {
        try {
            AddPushpinLeadsbyCity(info[i].ZipId, info[i].LeadId, info[i].SelPersonId, info[i].Zip, info[i].LeadBlockCode, info[i].Division, info[i].Market, info[i].County, info[i].CallType, info[i].LeadType, info[i].MdNumber, info[i].BirthDate, info[i].SequenceNumber, info[i].County, info[i].State, info[i].City, info[i].RawData, info[i].FirmName, info[i].LastName, info[i].FirstName, info[i].StreetAddress, info[i].LeadCity, info[i].LeadState, info[i].Telephone, info[i].SubSequenceNumber, info[i].Latitude, info[i].Longitude, info[i].SelDNC, info[i].PcLeadType, info[i].DncAfterDate, info[i].UserId);
        }
        catch (err) {
            alert(err);
        }
    }
    if (info.length > 0) {
        var lat = info[0].Latitude;
        var lon = info[0].Longitude;
        var velatlon = new VELatLong(lat, lon);
        LeadMap.SetCenterAndZoom(velatlon, 5);
    }
    leadLayer.Show();
    var divLoad = document.getElementById("divLoading");
    divLoad.style.visibility = 'hidden';
}

function AddPushpinLeadsbyCity(ZipId, LeadId, SelPersonId, Zip, LeadBlockCode, Division, Market, County, CallType, LeadType, MdNumber, BirthDate, SequenceNumber, County, State, City, RawData, FirmName, LastName, FirstName, StreetAddress, LeadCity, LeadState, Telephone, SubSequenceNumber, Latitude, Longitude, SelDNC, PcLeadType, DncAfterDate, UserId) {
    var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(Latitude, Longitude));
    var info = "Zip+4:" + Zip + "<br>" + "LeadBlockCode:" + LeadBlockCode + "<br>" + "Division:" + Division + "<br>" + "Market:" + Market + "<br>" + "County:" + County + "<br>" + "CallType:" + CallType + "<br>" + "LeadType:" + LeadType + "<br>" + "BirthDate:" + BirthDate + "<br>" + "SequenceNumber:" + SequenceNumber + "<br>" + "FirmName:" + FirmName + "<br>" + "LastName:" + LastName + "<br>" + "FirstName:" + FirstName + "<br>" + "StreetAddress:" + StreetAddress + "<br>" + "Preferred City:" + LeadCity + "<br>" + "State:" + LeadState + "<br>" + "Telephone:" + Telephone + "<br>" + "SelDNC:" + SelDNC + "<br>" + "DncAfterDate:" + DncAfterDate + "<br>";
    shape.SetCustomIcon(" <img src='../Content/Images/pin" + cityIndex(LeadCity) + ".gif'/> ");
    shape.SetDescription(info);
    shape.SetPhotoURL(ZipId);
    leadLayer.AddShape(shape);
}

function cityIndex(cityName) {
    var arrayIndex = 100;
    for (var i = 0; i < LeadsCityName.length; i++) {
        if (LeadsCityName[i] == cityName) {
            arrayIndex = i;
            break;
        }
    }
    if (arrayIndex == 100) {
        LeadsCityName.push(cityName);
        arrayIndex = LeadsCityName.length - 1;
    }
    arrayIndex = arrayIndex % 10;
    return arrayIndex;
}

function addLeadsToCart() {
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    var lblAgent = document.getElementById("ctl00_InfoContent_lblInfoAgent");
    var DrpOrderAgent = document.getElementById("ctl00_DetailsContent_drpOrderAgent");
    var findIndex = 0;
    lbactive.innerHTML = 0;
    lbbussiness.innerHTML = 0;
    lblapse.innerHTML = 0;
    lbneighbor.innerHTML = 0;
    CurOrderWeek = 0;

    for (var i = 0; i < DrpOrderAgent.length; i++) {
        if (DrpOrderAgent[i].text == lblAgent.innerText) {
            findIndex = i;
            break;
        }
    }

    DrpOrderAgent.options.remove(findIndex);

    var btn = document.getElementById("btnNextWeeek");
    btn.removeAttribute('disabled');

    var btn1 = document.getElementById("btnweek");
    btn1.setAttribute('disabled', 'disabled');

    alert('All leads have been successfully added to  the shopping cart');
}
function removeLeadsFromCart() {
    var zipIds = new Array();

    for (var i = 0; i < leadLayer.GetShapeCount(); i++) {
        var shape = leadLayer.GetShapeByIndex(i);
        var zipid = shape.GetPhotoURL();
        zipIds.push(zipid)
    }

    PageMethods.ManagerZipToCartNew(zipIds, '1', CurAgentName, CurOrderWeek, curMonth);
}
function CallBacklockMonth(month) {
    LockMonth = parseInt(month);
}

function IsLockOrder(LastOrderDate) {
    if (LastOrderDate != null && LastOrderDate.length >= 6) {
        var LastOrderMonth = LastOrderDate.substring(0, 2);
        var LastOrderYear = LastOrderDate.substring(2, 6);
        var NowMonth = PeriodMonth;
        var NowYear = PeriodYear;
        if (parseInt(curMonth) < NowMonth) {
            NowYear++;
        }
        var realMonth = curMonth;
        realMonth = parseInt(realMonth) + (12 * (NowYear - parseInt(LastOrderYear)));
        if (realMonth - parseInt(LastOrderMonth) < LockMonth) {
            return true;
        }
    }
    return false;
}

function ReturnIconName(cityName, lastOrder) {
    var lastMonth = "00";
    var arrayIndex = 100;
    for (var i = 0; i < OrderCityName.length; i++) {
        if (OrderCityName[i] == cityName) {
            arrayIndex = i;
            break;
        }
    }
    if (arrayIndex == 100) {
        OrderCityName.push(cityName);
        arrayIndex = OrderCityName.length - 1;
    }
    arrayIndex = arrayIndex % 10;
    if (lastOrder != '' && lastOrder != null) {
        lastMonth = lastOrder.substring(0, 2);
    }
    else {
        arrayIndex++;
        return 'pin' + arrayIndex + '.gif';
    }
    var MonthName = "J";
    switch (lastMonth) {
        case "01": MonthName = "J"; break;
        case "02": MonthName = "F"; break;
        case "03": MonthName = "M"; break;
        case "04": MonthName = "A"; break;
        case "05": MonthName = "MY"; break;
        case "06": MonthName = "JN"; break;
        case "07": MonthName = "JL"; break;
        case "08": MonthName = "AU"; break;
        case "09": MonthName = "S"; break;
        case "10": MonthName = "O"; break;
        case "11": MonthName = "N"; break;
        case "12": MonthName = "D"; break;
        default: MonthName = "pin";
    }
    arrayIndex = arrayIndex + 1;
    return MonthName + arrayIndex + ".gif";
}

function CallBackRuleEnable(result) {
    MDRuleEnable = result;
}
function CallBackRuleRepeatEnable(result) {
    MDRuleRepeatEnable = result;
}
function IsCurWeekLeads(assign) {
    if (assign == null || assign == '') {
        return false;
    }
    var assignmentName = assign.substring(assign.indexOf(' ') + 1, assign.length);
    assignmentName = assignmentName.replace(/\s+$|^\s+/g, ""); //trim
    var week = assign.split(' ')[0];
    if (assignmentName == CurAgentName && week == CurOrderWeek) {
        return true;
    }
    return false;
}

function addToCartRuleWithReason() {
    var reason = document.getElementById("textarea");
    if (reason.selectedIndex == 0) {
        alert('Please select the reason ,');
        return;
    }

    var str = new Array();
    str = CurLeadsRuleDisable.split(',');

    if (!CheckMDOrderRule(str[6])) {
        return;
    }

    PageMethods.InsertRepeatEnable(curMonth, str[13], reason.options[reason.selectedIndex].innerText);
    reason.selectedIndex = 0;
    var shape = map.GetShapeByID(str[12]);
    if (shape.GetMoreInfoURL().indexOf("false") != -1) //confirm it had ordered .
    {
        var lat = str[0];
        var lon = str[1];
        shape.SetCustomIcon(" <img src='../Content/Images/pinOrdered.gif'/> ");
        var Obj = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
        var info = 'Zip Code:' + str[3] + '<br>Preferred City: ' + str[4] + '<br>Terr: ' + str[5] + '<br>Active Count: ' + str[6] + '<br>Lasped Count:' + str[7] + '<br>Neighbor Count: ' + str[8] + '<br>Business Count: ' + str[9] + '<br>' + 'Assignment Name:' + CurOrderWeek + ' ' + CurAgentName + '<br>' + 'Last date ordered:' + str[14] + '<br>' + "Alternate City:" + str[15];
        var IsDLA = str[16];
        if (IsDLA=='true') {
            info = info + '<br>' + '<a href="#" onclick="divDefaultAssigment.style.visibility =\'visible\';divmask1.style.visibility = \'visible\';">Default Lead Assignment</a><br>';
        }
        var viewLeadText = '<br><a href="#" onclick="ViewLeads(' + "'" + str[13] + "'" + ')">View Leads</a>';
        shape.SetDescription(info + '<br><a href="#" onclick="RemoveFromCart(' + lat + ',' + lon + ",'" + str[2] + "','" + str[3] + "','" + str[4] + "','" + str[5] + "'," + str[6] + "," + str[7] + "," + str[8] + "," + str[9] + ",'" + 'true' + "','" + CurOrderWeek + ' ' + CurAgentName + "','" + str[12] + "','" + str[13] + "','" + str[14] + "','" + str[15] +"','"+str[16]+ "'" + ');">Remove from cart.</a>' + viewLeadText);
        shape.SetMoreInfoURL(shape.GetMoreInfoURL().replace('false', 'true'));
        PageMethods.ManagerZipToCart(str[13], '0', CurAgentName, CurOrderWeek, curMonth);
        addActive(str[6], str[7], str[8], str[9], str[5]);
    }
    document.getElementById("divMustOrder").style.visibility = 'hidden';
    document.getElementById("divmask1").style.visibility = 'hidden';
}
function UpdateDescrptionAssignMent(description, type) {
    var description1 = description.substring(description.indexOf("Last date"));
    description = description.substring(0, description.indexOf("Assignment Name:") + 16);
    if (type == '0') {
        description = description + CurOrderWeek + ' ' + CurAgentName + '<br>' + description1;
    }
    else {
        description = description + '<br>' + description1;
    }
    return description;
}
function IsAllowAddTocart(LastOrderDate) {
    var LastOrderMonth = LastOrderDate.substring(0, 2);
    var LastOrderYear = LastOrderDate.substring(2, 6);
    var NowMonth = PeriodMonth;
    var NowYear = PeriodYear;
    if (parseInt(curMonth) < NowMonth) {
        NowYear++;
    }
    var realMonth = curMonth;
    realMonth = parseInt(realMonth) + (12 * (NowYear - parseInt(LastOrderYear)));
    if (realMonth - parseInt(LastOrderMonth) <= 2) {
        return false;
    }
    return true;
}
function CallBackYear(result) {
    PeriodYear = result;
}
function CallBackMonth(result) {
    PeriodMonth = result;
}
function createAssign(assignName) {
    if (assignName != '') {
        var illegalChars = ['\\', '/', ':', '?', "*", '<', '>', '|', '"', '.'];
        for (i = 0; i < illegalChars.length; i++) {
            if (assignName.indexOf(illegalChars[i]) > -1) {
                alert("The assignment name can't contain illegal characters, \\ / : ?  * < > | .");
                return;
            }
        }
        PageMethods.IsAssignExist(assignName, callBackIsAssignExist);
    }
    else {
        alert("The assignment name can not be empty !");
    }
}

function callBackIsAssignExist(result) {
    var result1 = result.split('|');
    if (result1[0] == '0') {
        PageMethods.addAssign(result1[1], callBackAssignID);
        divCreateAssign.style.visibility = 'hidden';
        // alert('Assignment Creation', 'You have successfully created the ' + result1[1] + ' assignment. You may now add lead blocks to it.');
    }
    else {
        alert("This assignment name is already in use by you or another Market Director, please try another name.");
    }
}
function callBackAssignID(result) {
    lastAssignID = result;
    var assignName = document.getElementById("Text1").value;
    var tOption = document.createElement("Option");
    tOption.text = assignName;
    tOption.value = lastAssignID;
    document.all("ctl00_DetailsContent_drpOrderAgent").add(tOption);
    document.getElementById("Text1").value = '';
}

function SelectWeek() {
    IsReSelectWeek = true;
    var btn = document.getElementById("btnNext");
    btn.value = "Ok";
    divmask1.style.visibility = 'visible';
    divmassage_box2.style.visibility = 'visible';
    document.getElementById("ctl00_DetailsContent_drpOrderAgent").setAttribute('disabled', 'disabled');
    document.getElementById("ctl00_DetailsContent_drpOrderMonth").setAttribute('disabled', 'disabled');
    document.getElementById("Next1").setAttribute('disabled', 'disabled');
}
function callBackOtherPageCmd(result) {   //Do work where the command from page MDHomepage.
    var DrpOrderWeeks = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
    var LblAgent = document.getElementById("ctl00_InfoContent_lblInfoAgent");
    var LblWeek = document.getElementById("ctl00_InfoContent_lblInfoWeek");
    var btn = document.getElementById("btnNextWeeek");
    var DrpOrderCounty = document.getElementById("ctl00_DetailsContent_DrpOrderCounty");
    var DrpOrderMonth = document.getElementById("ctl00_DetailsContent_drpOrderMonth");
    var DrpOrderAgent = document.getElementById("ctl00_DetailsContent_drpOrderAgent");
    var para = new Array();
    para = result.split('|');
    letSelectWithValue(DrpOrderAgent, para[0], 0);
    letSelectWithValue(DrpOrderMonth, para[2], 1);
    letSelectWithValue(DrpOrderWeeks, para[3], 0);
    letSelectWithValue(DrpOrderCounty, para[4], 0);
    CurOrderWeek = parseInt(para[1]);
    curMonth = parseInt(para[2]);
    LblAgent.innerText = para[0];
    LblWeek.innerText = para[3];
    switch (OtherPageOperate) {
        case 'nextWeek':
            var Obj = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
            var btn = document.getElementById("btnNextWeeek");
            CurOrderWeek = parseInt(para[1]);
            document.getElementById("spanWeek").innerText = CurOrderWeek;
            document.getElementById("spanWeek1").innerText = CurOrderWeek;
            document.getElementById("ctl00_InfoContent_lblInfoWeek").innerText = CurOrderWeek;
            if (CurOrderWeek >= Obj.options[Obj.selectedIndex].innerText) {
                btn.setAttribute('disabled', 'disabled');
                var btn1 = document.getElementById("btnweek");
                btn1.removeAttribute('disabled');
            }
            UpdateCityByCounty();
            divmassage_box2.style.visibility = 'hidden';
            divmessage_box3.style.visibility = 'visible';
            divmask1.style.visibility = 'visible';
            PageMethods.ClearPara();
            break;
        case 'reSelect':
            IsReSelectWeek = true;
            var btn = document.getElementById("btnNext");
            btn.value = "Ok";
            divmask1.style.visibility = 'visible';
            divmassage_box2.style.visibility = 'visible';
            document.getElementById("ctl00_DetailsContent_drpOrderAgent").setAttribute('disabled', 'disabled');
            document.getElementById("ctl00_DetailsContent_drpOrderMonth").setAttribute('disabled', 'disabled');
            document.getElementById("Next1").setAttribute('disabled', 'disabled');
            break;
        case 'nextAgent':
            var divLoad = document.getElementById("divLoading");
            divLoad.style.visibility = 'visible';
            createMapForLead();
            PageMethods.ClearPara();
            break;
        case 'reCities':
            var Obj = document.getElementById("ctl00_DetailsContent_drpOrderWeeks");
            var btn = document.getElementById("btnNextWeeek");
            CurOrderWeek = parseInt(para[1]);
            document.getElementById("spanWeek").innerText = CurOrderWeek;
            document.getElementById("spanWeek1").innerText = CurOrderWeek;
            document.getElementById("ctl00_InfoContent_lblInfoWeek").innerText = CurOrderWeek;
            UpdateCityByCounty();
            divmassage_box2.style.visibility = 'hidden';
            divmessage_box3.style.visibility = 'visible';
            divmask1.style.visibility = 'visible';
            PageMethods.ClearPara();
            break;
    }

}
function letSelectWithValue(oListbox, itemValue, type) {   //type 0 select by text,1 by value
    for (i = 0; i < oListbox.options.length; i++) {
        if (type == 1) {
            if (oListbox.options[i].value == itemValue) {
                oListbox.options[i].selected = "selected";
            }
        }
        else {
            if (oListbox.options[i].innerText == itemValue) {
                oListbox.options[i].selected = "selected";
            }
        }
    }
}

function CallBackCity(result) {
    var citys = new Array();
    citys = result.split('|');
    var drpCity = document.getElementById('selectOrderCity');
    for (i = 0; i < citys.length; i++) {
        if (citys[i] != '') {
            var tOption = document.createElement("Option");
            tOption.text = citys[i];
            tOption.value = citys[i];
            drpCity.add(tOption);
            letSelectWithValue(drpCity, citys[i], 0);
        }
    }
    //Cities = result;
}
function createMapForLead() {
    if (map == null) {
        map = new VEMap('myMap1');
        map.LoadMap();
    }
    map.DeleteAllShapeLayers();
    shapeLayer = new VEShapeLayer();
    map.AddShapeLayer(shapeLayer);
    map.EnableShapeDisplayThreshold(false);
    lineLayer = new VEShapeLayer();
    leadsLayer = new VEShapeLayer();
    map.AddShapeLayer(lineLayer);
    map.AddShapeLayer(leadsLayer);
    var Obj = document.getElementById("ctl00_DetailsContent_DrpOrderCounty");
    PageMethods.IsOrderPeriod(CallBackIsOrderPeriod);
    var citySelect = document.getElementById("selectOrderCity");

    var county = Obj.options[Obj.selectedIndex].innerText;
    var countyList = new Array();
    if (county == 'All') {
        for (i = 1; i < Obj.options.length; i++) {
            countyList.push(Obj.options[i].text);
        }
    }
    else {
        countyList.push(county);
    }

    PageMethods.Pin(GetSelectItem(citySelect), countyList, curMonth, CallBackLeadAndPin);

}

function CallBackLeadAndPin(result) {
    TeerQueue = new Array();
    var serial = Sys.Serialization.JavaScriptSerializer;
    var info = serial.deserialize(result);
    selectIndex = document.getElementById("Select1").selectedIndex;
    for (var i in info) {
        try {
            AddPushpin(info[i].Latitude, info[i].Longitude, info[i].LeadBlockCode, info[i].ZipName, info[i].City, info[i].County,
                info[i].ActiveLeadCount, info[i].LapsedLeadCount, info[i].NeighborLeadCount, info[i].BusinessLeadCount, info[i].IsOrdered,
                info[i].UserAssigned, info[i].ZipId, info[i].LastOrderDate, info[i].SecondaryCity, info[i].IsDLA, info[i].RealActiveLeadCount, info[i].RealLapsedLeadCount);
            UpdateLatLon(info[i].Latitude, info[i].Longitude);
            BindFilterZipcode(info[i].ZipName);
        }
        catch (err) {
            alert(err);
        }
    }
    IsNeedPostback = false;
    CurOrderWeek = 0;
    var btn = document.getElementById("btnNextWeeek");
    btn.removeAttribute('disabled');
    var btn1 = document.getElementById("btnweek");
    btn1.setAttribute('disabled', 'disabled');
    divmask1.style.visibility = 'visible';
    divMapLead.style.visibility = 'visible';
    mapWithLeads.style.visibility = 'visible';
    LeadMap = new VEMap('mapWithLeads');
    LeadMap.LoadMap();
    leadLayer = new VEShapeLayer();
    LeadMap.AddShapeLayer(leadLayer);
    LeadsCityName = new Array();
    zipIds = new Array();

    for (var i = 0; i < shapeLayer.GetShapeCount(); i++) {
        var shape = shapeLayer.GetShapeByIndex(i);
        var str = new Array();
        str = shape.GetMoreInfoURL().split('|');
        var teer;
        var isOrder;

        if (!IsNeedPostback) {
            teer = str[2];
            isOrder = str[1];
        }
        else {
            teer = str[1];
            isOrder = str[8];
        }

        if (isOrder == 'true') {
            zipIds.push(str[0])
        }
    }
    PageMethods.LeadsPinWithCity(zipIds, CallBackleadsByCity);
}

function CallBackOperateType(result) {
    OtherPageOperate = result.toString();
    if (OtherPageOperate != '') {
        PageMethods.GetCity(CallBackCity);
        PageMethods.GetOtherPagePara(callBackOtherPageCmd);
    }
}
function SelecCities() {
    alert('Don\'t forget, the cities you selected are already highlighted. If you want to include those cities in your order you need to show them again. Select multiple files that are grouped together If you want to select multiple cities that are all grouped together:\n1.Select the first city and then press and hold the Shift key.\n2.While holding the shift key down click the last file. This will select all the cities in-between the first and last city.\n\nTo select multiple files that are not grouped together\n\nIf there are multiple cities you need to select but they are not grouped together:\n1.Select the first city you want to copy and then press and hold the Ctrl key.\n2.While holding down the Ctrl key, select each of the other cities you wish to select.')
    var lbneighbor = document.getElementById("ctl00_InfoContent_lbNeighborLead");
    var lbactive = document.getElementById("ctl00_InfoContent_lbActiveLead");
    var lbbussiness = document.getElementById("ctl00_InfoContent_lbBussinessLead");
    var lblapse = document.getElementById("ctl00_InfoContent_lbLapseLead");
    lbactive.innerHTML = 0;
    lbbussiness.innerHTML = 0;
    lblapse.innerHTML = 0;
    lbneighbor.innerHTML = 0;
    divmessage_box3.style.visibility = 'visible';
    divmask1.style.visibility = 'visible';
}